﻿using BnbjoyBackend.Site.Security;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using BnbjoyBackend.Site.Extends;
using System.Web.Routing;
using Newtonsoft.Json;
using Bnbjoy.Business.Model;
using BnbjoyBackend.Site.ConstantsNS;

namespace BnbjoyBackend.Site.Controllers
{
    public class AccountController : Controller
    {
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            ViewBag.Title = "宿说掌柜-专为民宿定制";

            //如果token都存在，那么表明已登录,直接跳转至首页
            if (AuthorizedUserManager.Instance.UserLoggedIn)
                Response.RedirectToRoute(
                new RouteValueDictionary{
                    { "Controller", "Home" },
                    { "Action", "Index" }});

            return View();
        }

        [HttpPost]
        public async Task<ActionResult> Login(LoginUserParam user)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    //校验用户名密码，得到access token
                    var passwordCredetial_TokenResponse = TokenManager.Instance.GetToken(user.UserName, user.Password, user.Store30Days);
                    if (passwordCredetial_TokenResponse.IsError)
                        return Json(new HttpPostResponse(HttpStatusCode.Forbidden, "用户名或密码错误"));

                    //存储access token和refresh token到cookie和session
                    AuthorizedUserManager.Instance.SetTokenInfo(user.UserName, passwordCredetial_TokenResponse.AccessToken, passwordCredetial_TokenResponse.RefreshToken);
                    //获取用户名，角色和权限信息，存储到session
                    UrlHelper helper = new UrlHelper(Request.RequestContext);
                    string rejectedUrl = helper.Action("Rejected", "Account");
                    //获取用户有权管理的Bnb列表
                    dynamic inManagedBnbsRes = await AuthorizedUserManager.Instance.GetCurrentBnbInfo();
                    List<dynamic> inManagedBnbs = null;
                    if (inManagedBnbsRes == null || (Common.IsPropertyExist(inManagedBnbsRes, "StatusCode") && inManagedBnbsRes.StatusCode == HttpStatusCode.Redirect))
                    {

                        return Json(new HttpPostResponse(HttpStatusCode.Redirect, rejectedUrl));
                    }
                    else
                    {
                        inManagedBnbs = Enumerable.ToList<dynamic>(inManagedBnbsRes);
                    }

                    //得到当前默认管理的目标bnb
                    if (Session[Constants.OnSelectBnbSession] == null)
                        Session[Constants.OnSelectBnbSession] = inManagedBnbs.FirstOrDefault();

                    var param = Session[Constants.OnSelectBnbSession] as dynamic;

                    dynamic userInfoRes = await AuthorizedUserManager.Instance.GetUserInfo((string)param.UserId, (string)param.RoleName, (string)param.BnbId);
                    if (userInfoRes == null)
                        return Json(new HttpPostResponse(HttpStatusCode.InternalServerError, "登录失败"));
                    else if (Common.IsPropertyExist(userInfoRes, "StatusCode") && userInfoRes.StatusCode == HttpStatusCode.Redirect)
                        return Json(userInfoRes); //服务返回需要跳转，告知js
                    else
                        //js捕获，会跳转至dashboard首页
                        return Json(new HttpPostResponse(HttpStatusCode.OK, "登录成功"));
                }
                else
                {
                    return Json(new HttpPostResponse(HttpStatusCode.Forbidden, "无效的登录请求"));
                }
            }
            catch (Exception ex)
            {
                return Json(new HttpPostResponse(HttpStatusCode.InternalServerError, "服务错误，登录失败"));
            }

        }

        public ActionResult Register()
        {
            ViewBag.Title = "宿说掌柜-用户注册";

            //如果token都存在，那么表明已登录,直接跳转至首页
            if (AuthorizedUserManager.Instance.UserLoggedIn)
                Response.RedirectToRoute(
                new RouteValueDictionary{
                    { "Controller", "Home" },
                    { "Action", "Index" }});

            return View();
        }

        [HttpPost]
        public async Task<ActionResult> Register(UserRegistrationParam user)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    var publicToken = AuthorizedUserManager.Instance.PublicAccessToken;
                    string userJson = JsonConvert.SerializeObject(user);
                    HttpPostResponse response = await ServiceManager.Instance.PostOpenService(publicToken, "account/register", userJson);
                    await this.Login(new LoginUserParam { UserName = user.UserName, Password = user.Password, Store30Days = false });
                    return Json(response);
                }
                else
                {
                    return Json(new HttpPostResponse(HttpStatusCode.Forbidden, "无效的注册请求"));
                }
            }
            catch (Exception ex)
            {
                return Json(new HttpPostResponse(HttpStatusCode.InternalServerError, "服务错误，注册失败"));
            }
        }

        [HttpPost]
        public async Task<ActionResult> SendMobileCaptcha(SendMobileCaptchaParam mobile)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    var publicToken = AuthorizedUserManager.Instance.PublicAccessToken;
                    HttpPostResponse response = await ServiceManager.Instance.PostOpenService(publicToken, "captcha/mobile", JsonConvert.SerializeObject(mobile));
                    return Json(response);
                }
                else
                {
                    return Json(new HttpPostResponse(HttpStatusCode.Forbidden, "无效的验证码请求"));
                }
            }
            catch (Exception ex)
            {
                return Json(new HttpPostResponse(HttpStatusCode.InternalServerError, "服务错误，发送失败"));
            }
        }

        [HttpPost]
        [BnbjoyAuthorize]
        public ActionResult Logout()
        {
            if (Request.IsAjaxRequest())
            {
                AuthorizedUserManager.Instance.CleanTokenAndSession();
                return Json(new HttpPostResponse(HttpStatusCode.OK, "用户成功注销"));
            }
            else
            {
                return Json(new HttpPostResponse(HttpStatusCode.Forbidden, "无效的注销请求"));
            }
        }

        public ActionResult Rejected()
        {
            ViewBag.Title = "宿说掌柜-访问受限";
            return View();
        }
    }
}